package com.shiro.realm;

/**
 * @author WxrStart
 * @create 2022-05-25 14:33
 */

import com.bean.User;
import com.service.IUserService;
import com.shiro.token.JWTToken;
import com.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;



/**
 * JwtRealm 只负责校验 JWTToken
 */
@Slf4j
public class JwtRealm extends AuthorizingRealm {
    @Autowired
    IUserService iUserService;

    /**
     * 限定这个 Realm 只处理我们自定义的 JWTToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        log.info("JwtRealm的supports调用了");
        return token instanceof JWTToken;
    }

    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        log.info("JwtRealm的doGetAuthenticationInfo调用了");
        JWTToken jwtToken = (JWTToken) authcToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AuthenticationException("JWT token参数异常！");
        }
        // 从 JWTToken 中获取当前用户email
        String email = JWTUtils.getClaimFiled(jwtToken.getCredentials(),"email");
        // 查询数据库获取用户信息
        User user = iUserService.findByEmail(email);

        // 用户不存在
        if (user == null) {
            throw new AuthenticationException("用户不存在！");
        }

        // 用户被锁定
        if (user.getStatus()!=1) {
            throw new AuthenticationException("该用户已被锁定,暂时无法登录！");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, email, getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("JwtRealm的doGetAuthorizationInfo调用了");
        // 获取当前用户
        User user= (User) SecurityUtils.getSubject().getPrincipal();
        // 查询数据库，获取用户的角色信息
        String userRole = user.getUserRole();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(userRole);
        return info;
    }

    @Override
    public String getName() {
        log.info("JwtRealm的getName调用了");
        return "JwtRealm";
    }
}
